/*
 * @Author: YNT 2501512800@qq.com
 * @Date: 2022-08-06 23:09:23
 * @LastEditors: YNT 2501512800@qq.com
 * @LastEditTime: 2022-09-04 15:18:39
 * @FilePath: \20220806后台\src\utils\service\auth.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
// 定义登录token的key(键名),在获取/存储的时候,通过这个key获取和存储
const ACCESS_TOKEN_KEY = "admin_access_token";
const REFRESH_TOKEN_KEY = "admin_refresh_token";

const setStorage = (key, value) => {
  try {
    localStorage.setItem(key, JSON.stringify(value));
    return true;
  } catch (e) {
    return false;
  }
};

const getStorage = (key, isObj = true) => {
  try {
    const value = localStorage.getItem(key);
    return isObj ? JSON.parse(value) : value;
  } catch (e) {
    return false;
  }
};

const clearStorage = (key) => {
  try {
    localStorage.removeItem(key);
    return true;
  } catch (e) {
    return false;
  }
};

const setToken = (accessToken, refreshToken) => {
  accessToken && localStorage.setItem(ACCESS_TOKEN_KEY, `${accessToken}`);
  refreshToken && localStorage.setItem(REFRESH_TOKEN_KEY, `${refreshToken}`);
};

const getToken = () => {
  return getStorage(ACCESS_TOKEN_KEY, false);
};
const getRefreshToken = () => {
  return getStorage(REFRESH_TOKEN_KEY, false);
};

const removeToken = () => {
  return clearStorage(ACCESS_TOKEN_KEY) && clearStorage(REFRESH_TOKEN_KEY);
};

module.exports = {
  setToken,
  removeToken,
  getToken,
  getRefreshToken,
  getStorage,
  setStorage,
  clearStorage,
};
